package com.ruoyi.sale.controller;


import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.sale.domain.Sale;
import com.ruoyi.sale.service.ISaleService;
import com.ruoyi.system.api.domain.SysUser;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/sale")
public class SaleController extends BaseController {

    @Autowired
    private ISaleService saleService;

    /**
     * 新增优惠券
     */
    @Log(title = "营销管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Sale sale)
    {
        if (!saleService.checkSaleNameUnique(sale))
        {
            return error("新增优惠券失败'" + sale.getName() + "'失败，优惠券已存在");
        }
        sale.setCreateBy(SecurityUtils.getUsername());
        return toAjax(saleService.insertSale(sale));
    }

    /**
     * 复制优惠券
     */
    @Log(title = "营销管理", businessType = BusinessType.INSERT)
    @PostMapping("/{saleId}")
    public AjaxResult copy(@PathVariable Long saleId)
    {
        Sale sale = saleService.selectSaleById(saleId);
        List<Sale> sales = saleService.selectSaleList1();
        sale.setSaleId(Collections.max(sales, Comparator.comparing(Sale::getSaleId)).getSaleId() +1);
        return toAjax(saleService.insertSale(sale));
    }

    /**
     * 显示全部优惠券
     */
    @GetMapping("/list")
    public TableDataInfo list(Sale sale)
    {
        startPage();
        List<Sale> list = saleService.selectSaleList(sale);
        return getDataTable(list);
    }
    /**
     * 查询详情
     */
    @GetMapping(value = "/{saleId}")
    public AjaxResult getInfo(@PathVariable Long saleId)
    {
        return success(saleService.selectSaleById(saleId));
    }
    /**
     * 删除优惠券
     */
    @Log(title = "优惠券管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{saleId}")
    public AjaxResult remove(@PathVariable Long saleId)
    {
        return toAjax(saleService.deleteSaleById(saleId));
    }

    /**
     * 修改
     */
    @Log(title = "优惠券管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Sale sale)
    {
        return toAjax(saleService.updateSale(sale));
    }

}
